package online.afeibaili.storebackendframework.server;

import online.afeibaili.storebackendframework.af.CouponInterface;
import online.afeibaili.storebackendframework.mapper.CouponMapper;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class GetCouponServer {
    @Autowired
    private CouponInterface couponInterface;
    @Autowired
    private CouponMapper couponMapper;

    public String getCoupon(String userId, long couponId) {
        if (couponMapper.isCount(couponId) == 1) {
            Map<String, Object> coupon = couponMapper.selectName(couponId);
            long expireTime = Long.parseLong(coupon.get("expireTime").toString());
            if (expireTime < System.currentTimeMillis()) {
                return "优惠券已过期,不可领取!";
            }
            Object name = coupon.get("name");
            if (name == null) {
                JSONArray jsonArray = new JSONArray();
                return getMessage(userId, couponId, jsonArray);
            } else {
                JSONArray jsonArray = new JSONArray(name);
                if (name.toString().contains(String.valueOf(userId))) {
                    return "已领取不可重复领取";
                } else {
                    return getMessage(userId, couponId, jsonArray);
                }
            }
        }
        return "优惠券不存在";
    }

    @NotNull
    private String getMessage(String userId, long couponId, JSONArray jsonArray) {
        jsonArray.put(userId);
        if (!couponInterface.insertCoupon(String.valueOf(couponId), userId)) {
            return "领取失败";
        }
        if (couponMapper.updateName(couponId, jsonArray.toString()) == 1) {
            return "领取成功";
        } else {
            return "优惠卷达到领取上线";
        }
    }
}
